<template>
  <div id="teamCardList">
    <van-card
        v-for="team in props.teamList"
        thumb="src/assets/ipad.jpeg"
        :desc="team.description"
        :title="`${team.name} 最大人数：${team.maxNum}`"
    >
      <template #tags>
        <van-tag plain type="danger"  style="margin-right: 8px; margin-top: 8px">
          {{ teamStatusEnum[team.teamStatus] }}
        </van-tag>
      </template>
      <template #bottom>
        <div>
          {{ `队伍人数：${team.hasJoinNum}/${team.maxNum}` }}
        </div>
        <div v-if="team.expireTime">
          {{`过期时间：${team.expireTime}`}}
        </div>
        <div v-if="team.createTime">
          {{`发布时间：${team.createTime}`}}
        </div>
      </template>
      <template #footer>
        <van-button size="mini" type="primary" v-if="team.id !== loginUser?.id" plain @click="preJoinTeam(team)">
          加入队伍
        </van-button>
      </template>
    </van-card>
    <van-dialog v-model:show="showPasswordDialog" title="请输入密码" @confirm="doJoinTeam" @cancel="doJoinCancel" show-cancel-button>
      <van-field v-model="password" placeholder="请输入密码" />
    </van-dialog>

  </div>
</template>
<script setup lang="ts">
import type {TeamType} from "../models/team";
import {teamStatusEnum} from "../constants/team.ts";
import myAxios from "../plugins/myAxios";
import {showFailToast, showSuccessToast} from "vant";
import {getCurrentUser} from "../services/user.ts";
import {onMounted, ref} from "vue";
import type {UserType} from "../models/user";
const showPasswordDialog = ref(false);
const password = ref('');

const joinTeamId = ref();
const doJoinCancel = () => {
  password.value = '';
  joinTeamId.value = 0;
}

const preJoinTeam = (team: TeamType) => {
  joinTeamId.value = team.id;
  if(team.teamStatus === 0){
    doJoinTeam();
    showPasswordDialog.value = false;
  } else {
    showPasswordDialog.value = true;
  }

}

const loginUser = ref<UserType>();
onMounted(async () => {
  loginUser.value = await getCurrentUser();
})
interface TeamCardListProps{
  teamList: TeamType[];
}

const props = withDefaults(defineProps<TeamCardListProps>(),{
  //@ts-ignore
  teamList: [] as TeamType[],
});

const doJoinTeam = async () => {
  if (!joinTeamId){
    return;
  }
  showPasswordDialog.value = true;
  const res = await myAxios.post('/team/join', {
    teamId: joinTeamId.value,
    password: password.value
  });
  if (res?.code === 0){
    showSuccessToast('加入成功');
  }else {
    showFailToast('加入失败' + (res.description?`${res.description}` : ''));
  }
}
</script>

<style scoped>
#teamCardList :deep(.van-image__img){
  height: 120px;
  object-fit: unset;
}
</style>